/**
 * 主题状态管理
 * 使用Pinia管理主题状态
 */

import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { themes, applyTheme, getCurrentTheme, initTheme } from '../utils/theme';

// 主题类型定义
interface Theme {
  name: string;
  id: string;
  colors: {
    primary: string;
    success: string;
    warning: string;
    danger: string;
    info: string;
    background: string;
    sidebar: string;
    header: string;
    text: string;
    border: string;
  };
  variables: {
    [key: string]: string;
  };
}

export const useThemeStore = defineStore('theme', () => {
  // 当前主题ID
  const currentThemeId = ref<string>(localStorage.getItem('theme') || 'default');
  
  // 检查当前主题是否有效（防止移除主题后出现无效主题）
  const isValidTheme = (themeId: string): boolean => {
    return themes.some(t => t.id === themeId);
  };
  
  // 如果当前主题无效（例如已被移除），则重置为默认主题
  if (!isValidTheme(currentThemeId.value)) {
    currentThemeId.value = 'default';
    localStorage.setItem('theme', 'default');
  }
  
  // 当前主题对象
  const currentTheme = computed<Theme>(() => {
    return themes.find(t => t.id === currentThemeId.value) || themes[0];
  });
  
  // 所有可用主题
  const availableThemes = computed<Theme[]>(() => themes);
  
  // 切换主题
  const setTheme = (themeId: string) => {
    currentThemeId.value = themeId;
    applyTheme(themeId);
  };
  
  // 重置为默认主题
  const resetTheme = () => {
    setTheme('default');
  };
  
  // 初始化主题
  const initializeTheme = () => {
    initTheme();
    currentThemeId.value = localStorage.getItem('theme') || 'default';
  };
  
  return {
    currentThemeId,
    currentTheme,
    availableThemes,
    setTheme,
    resetTheme,
    initializeTheme
  };
});